// JWT 验证守卫
import type { ExecutionContext } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { Reflector } from '@nestjs/core';
import type { Observable } from 'rxjs';
import { BusinessException } from '../exceptions/business.exception';
import { IS_PUBLIC_KEY } from './public.decorator';

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor(private reflector: Reflector) {
    super();
  }
  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    const request = context.switchToHttp().getRequest();
    if (isPublic) {
      if (request.headers.token) {
        // 如果 token 存在，就验证 token 并把用户信息添加到 request 中
        return super.canActivate(context);
      }
      return true;
    }
    if (!request.headers.token) {
      BusinessException.throwForbidden();
    }
    return super.canActivate(context);
  }
  handleRequest(err, user, info) {
    // 根据具体的情况，你可能想要调整这些条件
    if (err) {
      BusinessException.throwForbidden();
    }
    return user;
  }
}
